package com.hospital.hospitalserver.service;

import com.hospital.hospitalserver.entity.PatientMasterDTO;
import com.hospital.hospitalserver.entity.PatientVisitDTO;
import com.hospital.hospitalserver.entity.Vo.PatientMaster;
import com.hospital.hospitalserver.entity.query.DoctorPatientQuery;
import com.hospital.hospitalserver.enums.ResultCodeEnum;
import com.hospital.hospitalserver.exception.CustomException;
import com.hospital.hospitalserver.mapper.PatientMasterMapper;
import com.hospital.hospitalserver.mapper.PatientVisitMapper;
import com.hospital.hospitalserver.util.PagerData;
import com.hospital.hospitalserver.util.Response;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

/**
 * 患者挂号相关操作实现方法
 * */
@Service
@RequiredArgsConstructor
public class PatientVisitService {
    private final PatientVisitMapper patientVisitMapper;
    private final PatientMasterMapper patientMasterMapper;

    /**
     * 根据当前医生id获取其所有患者挂号数据总数
     * 带条件查询
     * */
    private Integer getPatientVisitCountsBySearch(DoctorPatientQuery query){
        return patientVisitMapper.getPatientVisitCountsBySearch(query);
    }

    /**
     * 计算分页
     * */
    private Integer getPatientVisitPageTotalBySearch(DoctorPatientQuery query){
        Integer patientVisitCounts = getPatientVisitCountsBySearch(query);
        Integer pageTotal = 1;//设置初始页码为1
        //数据总条数除以pageSize每页显示条数，如取余数求模，如果有余数，页码+1
        //如果可以整除，则页码等于数据总数除以pageSize
        pageTotal = patientVisitCounts/ query.getPageSize();
        if(patientVisitCounts% query.getPageSize()>0){
            pageTotal += 1;
        }
        return pageTotal;
    }

    /**
     * 根据当前医生id获取其所有患者挂号分页数据
     * 带条件查询
     * */
    private List<PatientVisitDTO> getPatientVisitPagerDataBySearch(DoctorPatientQuery query){
        Integer currentPage = query.getCurrentPage();
        Integer startIndex = (currentPage -1)* query.getPageSize();
        query.setStartIndex(startIndex);
        return patientVisitMapper.getPatientVisitListBySearch(query);
    }

    /**
     * 装载分页数据传给前端API
     * */
    @Transactional //添加事务管理
    public Response getPatientVisitDataBySearch(DoctorPatientQuery query){
        PagerData pagerData = new PagerData();
        pagerData.setTotal(getPatientVisitCountsBySearch(query));
        pagerData.setPageTotal(getPatientVisitPageTotalBySearch(query));
        pagerData.setData(getPatientVisitPagerDataBySearch(query));
        return Response.success(pagerData);
    }

    /**
     * 更新患者状态
     * */
    @Transactional
    public Response updatePatientVisitStatus(PatientVisitDTO request){
        // 1. 更新患者挂号状态
        Integer count = patientVisitMapper.updatePatientVisitStatus(request);
        if(count>0){
            //更新就诊状态成功后
            //2. 检查患者档案是否存在，根据用户身份证唯一编号查询，如果没有则新建
            String patientIdNumber = request.getId_number();
            PatientMaster existingPatientMaster = patientMasterMapper.getPatientMasterDataByIdNumber(patientIdNumber);

            Integer patientId;
            if (existingPatientMaster != null) {
                // 存在则不做操作
            } else {
                // 不存在，则新建患者档案
                PatientMasterDTO patientMasterDTO = new PatientMasterDTO();
                patientMasterDTO.setPatient_no(request.getId_number()); // 身份证作为档案编号且唯一
                patientMasterDTO.setPatient_name(request.getPatient_name()); // 患者姓名
                patientMasterDTO.setId_number(request.getId_number()); //身份证号
                // 获取性别和生日
                patientMasterDTO.setGender(request.getPatient_gender()); //性别
                patientMasterDTO.setBirth_date(calculateBirthDateFromIdNumber(request.getId_number())); // 新增生日计算
                patientMasterDTO.setPhone_number(request.getPhone_number()); // 电话

                //这样可以获取到新建患者档案id
                patientId = patientMasterMapper.insert(patientMasterDTO);
                request.setPatient_id(patientId);

                // 验证patientId是否有效
                if (patientId == null || patientId == 0) {
                    throw new CustomException(ResultCodeEnum.ERROR, "患者档案创建失败，未生成有效ID");
                }
            }

            return Response.success();
        }
        return Response.error();
    }
    /**
     * 根据身份证号计算出生日期
     */
    private LocalDate calculateBirthDateFromIdNumber(String idNumber) {
        if (idNumber == null || idNumber.length() != 18) {
            throw new CustomException(ResultCodeEnum.ERROR, "身份证号格式不正确");
        }

        try {
            String birthDateStr = idNumber.substring(6, 14); // 提取出生日期部分
            int year = Integer.parseInt(birthDateStr.substring(0, 4));
            int month = Integer.parseInt(birthDateStr.substring(4, 6));
            int day = Integer.parseInt(birthDateStr.substring(6, 8));

            return LocalDate.of(year, month, day);
        } catch (Exception e) {
            throw new CustomException(ResultCodeEnum.ERROR, "身份证号出生日期解析失败");
        }
    }

    /**
     * 根据挂号编号查询当天患者的挂号是否有效
     * */
    public Response validatePatientVisitAppointmentId(PatientVisitDTO request){
        return Response.success(patientVisitMapper.validatePatientVisitAppointmentId(request.getAppointment_id()));
    }
}
